package com.chushouya.controller.common;


import com.general.framework.core.enums.BusinessType;
import com.general.framework.core.lang.IdTakes;
import com.general.framework.core.lang.Jsons;
import com.general.framework.core.lang.Strings;
import com.general.framework.web.annotations.Log;
import com.chushouya.manager.dto.admin.oss.OssStsDTO;
import com.general.framework.core.enums.LimitType;
import com.general.framework.core.exception.Ex;
import com.general.framework.core.schema.Response;
import com.general.framework.core.utils.FileUtils;
import com.general.framework.web.annotations.RateLimiter;
import com.chushouya.manager.service.admin.OssService;
import com.chushouya.common.constant.ServiceType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Api(tags = "文件管理")
@RestController
@RequestMapping(ServiceType.COMMON + "/fileUpload")
@Slf4j
public class FileUploadController {

    @Resource
    private OssService ossService;

    @ApiOperation("上传图片(不推荐使用该方式，getOssSts)")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "folderPath", value = "文件夹路径(不传时存放在根目录)", dataType = "String", paramType = "query"),
        @ApiImplicitParam(name = "imageName", value = "用户自定义命名(不要文件后缀,不传时系统uuid命名)", dataType = "String", paramType = "query"),
    })
    @PostMapping("/uploadImage")
    @RateLimiter(time = 10, count = 20, limitType = LimitType.IP, message = "操作频繁，请稍后再试")
    public Response<String> uploadImage(@RequestParam("file") MultipartFile file, String folderPath, String imageName) throws IOException {
        final String fullPath = this.uploadHandler(file, folderPath, imageName);
        return Response.success(fullPath);
    }

    private String uploadHandler(@RequestParam("file") MultipartFile file, String folderPath, String imageName) throws IOException {
        if (Objects.isNull(file)) {
            throw Ex.business("文件不能为空");
        }
        if (Strings.isBlank(imageName)) {
            imageName = null;
        }
        final String originalFilename = file.getOriginalFilename();
        String suffix = FileUtils.getFileType(originalFilename);
        if (Strings.isBlank(suffix)) {
            suffix = "png";
        }
        final String fileName = Strings.defaultString(imageName, IdTakes.takeUUID()).concat(".").concat(suffix);
        String filePath;
        if (Strings.isEmpty(folderPath)) {
            filePath = fileName;
        } else {
            filePath = folderPath.concat("/").concat(fileName);
        }
        final String fullPath = ossService.uploadImage(file.getInputStream(), filePath, file.getContentType());
        log.info("===>图片上传成功:{}", fullPath);
        return fullPath;
    }

    @ApiOperation("小程序上传图片")
    @RateLimiter(time = 10, count = 20, limitType = LimitType.IP, message = "操作频繁，请稍后再试")
    @PostMapping("/liteUploadImage")
    public void doPost(@RequestParam("file") MultipartFile file, String folderPath, String imageName, HttpServletResponse response) throws IOException {
        final String fullPath = this.uploadHandler(file, folderPath, imageName);
        response.setCharacterEncoding("UTF-8");
        response.getWriter().print(Jsons.toJsonString(Response.success(fullPath)));
    }

    @GetMapping("/getOssSts")
    @ApiOperation("获取存储的STS授权信息")
    @RateLimiter(time = 10, count = 2)
    @Log(businessType = BusinessType.VIEW)
    public Response<OssStsDTO> getOssSts(String basePath) {
        return Response.success(ossService.getOssSts(basePath));
    }

}
